package com.codered;

import java.util.Calendar;
import java.util.TimeZone;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class CoderedActivity extends Activity {
	/**
	 * Variables
	 */
	
	// Constants
	private static String TAG = "CoderedActivity";
	public static boolean DEBUG = true;

	
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Start the Bluetooth Service
        startBluetoothService();
        
        //start Alarm Manager
        startAlarmManager();
    }
    
    
    /**
     * Starts the Bluetooth service
     * which turns bluetooth on
     */
	protected void startBluetoothService() {
    	if (DEBUG) Log.i(TAG, "startBluetoothService");
    	Intent intent = new Intent(this, BluetoothService.class);
    	startService(intent);
    }
	
	/**
	 * Start the Alarm Manager
	 * 
	 */
	protected void startAlarmManager() {
		if (DEBUG) Log.i(TAG, "startAlarmManager");
		//Define the intent that the Alarm will trigger
		Intent recurring = new Intent(this, RecurringService.class);
	    PendingIntent recurringDownload = PendingIntent.getService(this, 0, recurring, PendingIntent.FLAG_CANCEL_CURRENT);

	    //Determine the current hour of day.
	    Calendar rightNow = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
	    int hour = rightNow.get(Calendar.HOUR_OF_DAY);
	    
	    //Determine the time for the start of the next hour.
	    Calendar updateTime = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
	    updateTime.setTimeZone(TimeZone.getTimeZone("GMT"));
	    updateTime.set(Calendar.HOUR_OF_DAY, hour++);
	    updateTime.set(Calendar.MINUTE, 00);
	    
	    //Set the alarm to trigger in intent
		AlarmManager alarmService = (AlarmManager) getSystemService(ALARM_SERVICE);
		alarmService.setRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_HALF_HOUR, recurringDownload);
	}
	
	
	
	
	public void writeNote(View button) {
    	if (DEBUG) Log.i(TAG, "write note clicked");
    	Intent intent = new Intent(this, NoteActivity.class);
    	startActivity(intent);
	}
	
	public void forceRecurring(View button) {
		if (DEBUG) Log.i(TAG, "recurring action button clicked");
		Intent intent = new Intent(this, RecurringService.class);
		startService(intent);
	}
    
	public void forceUpload(View button) {
		if (DEBUG) Log.i(TAG, "upload action button clicked");
		Intent intent = new Intent(this, UploadService.class);
		startService(intent);
	}

}